﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LibEBML
{
    public class Document : IDisposable
    {
        public EBMLContainer Header { get; protected set; }
        public IList<EBMLContainer> Segments { get; protected set; }
        public ElementFactory Factory { get; private set; }


        public Document(Stream Source)
        {
            var f = new ElementFactory(this);
            Initialize(Source, f);
        }
        public Document(Stream Source, ElementFactory factory)
        {
            Initialize(Source, factory);
        }
        protected virtual void Initialize(Stream Source, ElementFactory factory)
        {
            this.Factory = factory;
            BaseSource = Source;
            GetHeader();
            GetSegments();
        }

        protected Stream BaseSource;

        protected void GetHeader()
        {
            Header = Factory.GetElement(BaseSource, 0) as EBMLContainer;
            //Header = new EBMLHeader(BaseSource, 0, Size, v1.Length + v2.Length);
        }
        protected void GetSegments()
        {
            Segments = new List<EBMLContainer>();
            var pos = Header.Length;
            while (pos < BaseSource.Length)
            {
                EBMLContainer seg = Factory.GetElement(BaseSource, pos) as EBMLContainer;
                Segments.Add(seg);
                pos += seg.Length;
            }
        }

        public virtual void Dispose()
        {
            if (Header != null)
            {
                Header.Dispose();
            }
            if (Segments != null)
            {
                foreach (var item in Segments)
                {
                    item.Dispose();
                }
            }
            BaseSource = null;
        }
    }
}
